<style lang="less" scoped>
  /deep/.el-dialog--center .el-dialog__body {
    padding: 30px 30px 51px 25px;
  }
  /deep/.el-form-item__label {
    padding-right: 0;
  }
</style>
<template>
  <el-dialog v-el-drag-dialog
    id="imgModify"
    :title="dialogTitle"
    :append-to-body='true'
    :visible.sync="imgModifyShow"
    :before-close="ImgModifyClose"
    width="940px"
    top="3%"
    center>
    <div class="of">
      <el-form
      :model="imgModifyData"
      :rules="imgModifyRule"
      ref="imgModifyForm"
      class="of"
      label-position="right"
      label-width="100px"
      :disabled="dialogType === 'view'">
        <div class="of fl bbd pb25" style="width: 885px;">
          <div class="f16 mb20 clr_333">患者信息修改</div>
          <div class="w100 clear_fixed">
            <el-form-item label="患者编号：" label-width="84px" class="fl" prop="patient_id">
              <el-input
                size="medium"
                placeholder="请输入患者编号"
                style="width:180px;"
                v-model="imgModifyData.patient_id"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="患者姓名：" label-width="130px" class="fl" prop="other_patient_name">
              <el-input
                size="medium"
                placeholder="请输入患者姓名"
                style="width:180px;"
                v-model="imgModifyData.other_patient_name"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="拼音信息：" label-width="130px" class="fl" prop="patient_name">
              <el-input
                size="medium"
                placeholder="请输入拼音信息"
                style="width:180px;"
                v-model="imgModifyData.patient_name"
                clearable>
              </el-input>
            </el-form-item>
          </div>
          <div class="w100 clear_fixed mt10">
            <el-form-item label="性别：" label-width="84px" class="fl" prop="patient_sex">
              <div class="" style="line-height: 40px">
                <el-radio-group v-model="imgModifyData.patient_sex">
                  <el-radio label="M">男</el-radio>
                  <el-radio label="F">女</el-radio>
                  <el-radio label="O">未知</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
            <el-form-item label="出生日期：" label-width="122px" class="fl" prop="patient_birth_date">
              <el-date-picker
                v-model="imgModifyData.patient_birth_date"
                align="right"
                type="date"
                placeholder="选择日期"
                size="medium"
                style="width:180px;"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="birthDayPickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="年龄：" label-width="130px" class="fl" prop="patient_age">
              <el-input-number style="width: 90px" size="medium" v-model="patientAgeNum" controls-position="right" @change="patientAgeNumChange" :min="0"></el-input-number>
              <el-select v-model="patientAgeType" @change="patientAgeTypeChange" size="medium" style="width:70px" class="ml20">
                <el-option value="Y" label="岁"></el-option>
                <el-option value="M" label="月"></el-option>
                <el-option value="W" label="周"></el-option>
                <el-option value="D" label="日"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="of fl pb10 mt26" style=" width: 885px;">
          <div class="f16 mb20 clr_333">检查信息修改</div>
          <div class="w100 clear_fixed">
            <el-form-item label="检查编号：" label-width="84px" class="fl" prop="accession_number">
              <el-input
                size="medium"
                placeholder="请输入检查编号"
                style="width:180px;"
                v-model="imgModifyData.accession_number"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="检查类型：" label-width="130px" class="fl">
              <el-select disabled v-model="imgModifyData.modalities_in_study" placeholder="请选择检查类型" size="medium" style="width:180px">
                <el-option
                  v-for="(item, index) in modalityTypeOptions"
                  :value="item.value"
                  :label="item.label"
                  :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="w100 clear_fixed mt10">
            <el-form-item label="检查描述：" label-width="84px">
              <el-input
                size="medium"
                placeholder="请输入检查描述"
                style="width:100%;"
                v-model="imgModifyData.study_description"
                clearable>
              </el-input>
            </el-form-item>
          </div>
          <div class="w100 clear_fixed mt10">
            <el-form-item label="检查唯一号：" label-width="84px" prop="study_instance_uid">
              <el-input
                size="medium"
                placeholder="请输入检查唯一号"
                style="width:100%;"
                v-model="imgModifyData.study_instance_uid"
                clearable>
              </el-input>
            </el-form-item>
          </div>
          <div class="w100 clear_fixed mt10">
            <el-form-item label="检查日期：" label-width="84px" class="fl" prop="study_date_time">
              <el-date-picker
                v-model="studyDate"
                align="right"
                type="date"
                placeholder="检查日期"
                size="medium"
                style="width:180px;"
                value-format="yyyy-MM-dd"
                :picker-options="checkDayPickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="检查时间：" label-width="130px" class="fl" prop="study_description">
              <el-time-picker
                v-model="studyTime"
                size="medium"
                style="width:180px;"
                value-format="HH:mm:ss"
                placeholder="选择时间 ">
              </el-time-picker>
            </el-form-item>
            <el-tooltip placement="right" class="lh35 ml15" popper-class="imgModifyCheckTimeTip">
              <div slot="content">
                检查日期和时间的修改功能仅用于
                <br/>
                影像设备时间发错误时。
                <br>
                由于日期和时间被修改而导致的法
                <br>
                律纠纷，我司不承担责任。
              </div>
              <i class="iconfont clr_ef8900">&#xe687;</i>
            </el-tooltip>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer mt20 fr">
        <el-button @click="ImgModifyClose" size="small" class="mr20">关闭</el-button>
        <el-button v-if="dialogType !== 'view'" type="primary" @click="ImgModifySave('imgModifyForm')" size="small">确 定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import moment from 'moment'

export default {
  data () {
    let requiredValidator = function (tip) {
      return (rule, value, callback) => {
        if(value === '' || !value) {
          callback(new Error(tip))
        }else {
          callback()
        }
      }
    }
    let ageValidator = (rule, value, callback) => {
      if(this.patientAgeNum === '' || !this.patientAgeNum) {
        callback()
      }else if(!Number.isInteger(this.patientAgeNum)) {
        this.patientAgeNum = parseInt(this.patientAgeNum)
        if(this.patientAgeType === 'Y' && this.patientAgeNum > 999) {
          callback(new Error('年龄超出范围'))
        }else {
          callback()
        }
      }else if(Number.isInteger(this.patientAgeNum)) {
        if(this.patientAgeType === 'Y' && this.patientAgeNum > 999) {
          callback(new Error('年龄超出范围'))
        }else {
          callback()
        }
      }else {
        callback()
      }
    }
    let dateValidator = (rule, value, callback) => {
      if(this.studyDate === '' || !this.studyDate) {
        callback(new Error('请选择检查日期'))
      }else {
        callback()
      }
    }
    let timeValidator = (rule, value, callback) => {
      if(this.studyTime === '' || !this.studyTime) {
        callback(new Error('请选择检查时间'))
      }else {
        callback()
      }
    }
    return {
      dialogTitle: '',
      imgModifyData: {
        patient_name: '',
        other_patient_name: '',
        patient_id: '',
        patient_sex: 'M',
        patient_age: '',
        accession_number: '',
        modalities_in_study: '',
        patient_birth_date: '',
        study_description: '',
        study_instance_uid: '',
        study_date_time: ''
      },
      imgModifyRule: {
        patient_id: [{
          trigger: 'blur',
          validator: requiredValidator('请输入患者编号')
        }],
        other_patient_name: [{
          trigger: 'blur',
          validator: requiredValidator('请输入患者姓名')
        }],
        patient_name: [{
          trigger: 'blur',
          validator: requiredValidator('请输入拼音信息')
        }],
        patient_sex: [{
          trigger: 'blur',
          validator: requiredValidator('请选择性别')
        }],
        // patient_birth_date: [{
        //   trigger: 'blur',
        //   validator: requiredValidator('请选择出生日期')
        // }],
        patient_age: [{
          trigger: 'blur',
          validator: ageValidator
        }],
        accession_number: [{
          trigger: 'blur',
          validator: requiredValidator('请输入检查编号')
        }],
        study_instance_uid: [{
          trigger: 'blur',
          validator: requiredValidator('请输入检查唯一号')
        }],
        study_date_time: [{
          trigger: 'blur',
          validator: dateValidator
        }],
        study_description: [{
          trigger: 'blur',
          validator: timeValidator
        }]
      },
      patientAgeNum: '',
      patientAgeType: '',
      studyDate: '',
      studyTime: '',
      originalStudyDate: '',
      originalStudyTime: '',
      modalityTypeOptions: [
        {
          value: 'CT',
          label: 'CT'
        },
        {
          value: 'CR',
          label: 'CR'
        },
        {
          value: 'MR',
          label: 'MR'
        },
        {
          value: 'NM',
          label: 'NM'
        },
        {
          value: 'DX',
          label: 'DX'
        },
        {
          value: 'ES',
          label: 'ES'
        },
        {
          value: 'MG',
          label: 'MG'
        },
        {
          value: 'RF',
          label: 'RF'
        },
        {
          value: 'SC',
          label: 'SC'
        },
        {
          value: 'US',
          label: 'US'
        },
        {
          value: 'XA',
          label: 'XA'
        },
        {
          value: 'OT',
          label: 'OT'
        },
        {
          value: '-1',
          label: '全部'
        }
      ], // 检查类型
      birthDayPickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      checkDayPickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      isFirstLoadAge: 1, // 第一次加载不触发出生日期的watch,后面修改才触发出生日期的watch
    }
  },
  props: ['imgModifyShow', 'rowId', 'dialogType'],
  watch: {
    dialogType (newVal) { // 修改弹窗标题
      this.dialogTitle = newVal === 'view' ? '查看' : newVal === 'modify' ? '影像修改' : ''
    },
    imgModifyShow (newVal) {
      if (newVal) {
        this.getCheckInfo(this.rowId)
      }else {
        this.isFirstLoadAge = 1
      }
    },
    isFirstLoadAge(newVal) {
      console.log(newVal)
    },
    patientAgeNum(newVal) {
      this.imgModifyData.patient_age = newVal + this.imgModifyData.patient_age.substring(this.imgModifyData.patient_age.length - 1, this.imgModifyData.patient_age.length)
      console.log(newVal)
      // 当前时间
      // let currentDate = new Date()
      // let currentYear = currentDate.getFullYear()
      // let currentMonth = currentDate.getMonth() + 1
      // let currentDay = currentDate.getDate()

      // // 出生日期和年龄联动  年龄值最低为1,必填
      // if(newVal && !this.patientAgeType) { // 1. 改变年龄值(不为空),如果年龄类型为空:不做处理
      //   return
      // }else if(newVal && this.patientAgeType && this.imgModifyData.patient_birth_date) { // 2. 改变年龄值(不为空),如果年龄类型不为空:根据年龄值和年龄类型计算出生日期
      //   if(this.patientAgeType === 'Y') {
      //     // this.imgModifyData.patient_birth_date = (currentYear - this.patientAgeNum) + '-' + '01-01 00:00:00'
      //   }else if(this.patientAgeType === 'M') {

      //   }else if(this.patientAgeType === 'D') {

      //   }
      // }else if(newVal && this.patientAgeType && !this.imgModifyData.patient_birth_date) {

      // }
    },
    patientAgeType(newVal) {
      this.imgModifyData.patient_age = this.imgModifyData.patient_age.substring(0, this.imgModifyData.patient_age.length - 1) + newVal
      console.log(newVal)
      // 出生日期和年龄联动  年龄类型必填
      // 1. 改变年龄类型(不为空),如果年龄值为空:不做处理
      // 2. 改变年龄类型(不为空),如果年龄值不为空:根据年龄值和年龄类型计算出生日期
    },
    'imgModifyData.patient_birth_date': {
      handler: function (newVal) { // 出生日期和年龄联动  出生日期必填
        console.log(newVal)
        if(this.isFirstLoadAge === 1) {
          return
        }
        if(!newVal) { // 3. 清空出生日期:清空年龄值,默认年龄类型为'岁'
          // this.$nextTick(() => {
          //   this.patientAgeNum = 1
          // })
          // this.patientAgeType = 'Y'
          return
        }
        console.log(moment(newVal).format('DD'))
        // 选择时间
        let year = parseInt(moment(newVal).format('YYYY'))
        let month = parseInt(moment(newVal).format('MM'))
        let day = parseInt(moment(newVal).format('DD'))
        // 当前时间
        let currentDate = new Date()
        let currentYear = currentDate.getFullYear()
        let currentMonth = currentDate.getMonth() + 1
        let currentDay = currentDate.getDate()
        // 1. 选择出生日期,年龄类型为空:默认年龄类型为'岁'
        if(newVal && this.patientAgeType === '') {
          this.patientAgeType = 'Y'
          let yearOld = currentYear - year
          // 当前日期年份,岁数为1
          if(currentYear === year) {
            yearOld = 1
          }
          // 月份大于当前时间月份,岁数减1
          if(currentMonth < month) {
            yearOld --
          }
          // 月份相同,日大于当前时间日,岁数减1
          if(currentMonth === month && currentDay < day) {
            yearOld --
          }
          this.patientAgeNum = yearOld
        }else if(newVal && this.patientAgeType !== '') {
          // 2. 选择出生日期,年龄类型存在:根据年龄类型计算年龄值
          if(this.patientAgeType === 'Y') { // 年龄类型为'岁'
            let yearOld = currentYear - year
            if(currentYear === year) { // 当前日期年份,岁数为1
              yearOld = 1
            }
            if(currentMonth < month) { // 月份大于当前时间月份,岁数减1
              yearOld --
            }
            if(currentMonth === month && currentDay < day) { // 月份相同,日大于当前时间日,岁数减1
              yearOld --
            }
            this.patientAgeNum = yearOld
          }else if(this.patientAgeType === 'M') { // 年龄类型为'月'
            let yearOld = currentYear - year
            let monthOld = currentMonth - month
            if(yearOld === 0 && monthOld === 0) {
              monthOld = 1
            }else if(yearOld !== 0 && (monthOld > 0 || monthOld === 0)) {
              monthOld = yearOld * 12 + monthOld
            }else if(yearOld !== 0 && monthOld < 0) {
              monthOld = ((12 - month) + currentMonth) + (yearOld - 1) * 12
            }
            this.patientAgeNum = monthOld
          }else if(this.patientAgeType === 'D') { // 年龄类型为'日'
            let currentTime = currentDate.getTime()
            console.log(newVal)
            // console.log(time)
            // console.log(currentTime)
            // let dayOld = (currentTime - time) / 1000 / 60 / 60 / 24
            // console.log(dayOld)
            // console.log(parseInt(dayOld))
            // if(dayOld === 0) {
            //   dayOld = 1
            // }
            console.log(moment(currentTime).diff(moment(newVal), 'days'))
            let dayOld = moment(currentTime).diff(moment(newVal), 'days')
            if(dayOld === 0) {
              dayOld = 1
            }
            this.patientAgeNum = dayOld
          }else if(this.patientAgeType === 'W') { // 年龄类型为'周'
            let weekOld = 1
            let currentTime = currentDate.getTime()
            let dayOld = moment(currentTime).diff(moment(newVal), 'days')
            console.log(dayOld / 7)
            if(dayOld === 0) {
              weekOld = 1
            }else if(dayOld / 7 < 1) {
              weekOld = 1
            }else {
              weekOld = Math.floor(dayOld / 7)
            }
            this.patientAgeNum = weekOld
          }
        }
      },
    },
    studyDate(newVal) {
      console.log(newVal)
      // const studyDate = this.studyDate ? this.studyDate : ''
      // const studyTime = this.studyTime ? this.studyTime : ''
      if(!this.studyTime) {
        this.imgModifyData.study_date_time = newVal ? newVal : ''
      }else {
        this.imgModifyData.study_date_time = newVal ? newVal + ' ' + this.studyTime : this.studyTime
      }
    },
    studyTime(newVal) {
      console.log(newVal)
      if(!this.studyDate) {
        this.imgModifyData.study_date_time = newVal ? newVal : ''
      }else {
        this.imgModifyData.study_date_time = newVal ? this.studyDate + ' ' + newVal : this.studyDate
      }
    }
  },
  methods: {
    patientAgeNumChange() {
      this.imgModifyData.patient_birth_date = null
    },
    patientAgeTypeChange() {
      this.imgModifyData.patient_birth_date = null
    },
    async getCheckInfo (id) {
      const res = await this.$pacsApi.pacsApi.getCheckInfo(id)
      const { code, data } = res
      if (code === 0) {
        console.log(data)
        this.imgModifyData = data
        this.patientAgeNum = data.patient_age.substring(0, data.patient_age.length - 1)
        this.patientAgeType = data.patient_age.substring(data.patient_age.length - 1, data.patient_age.length)
        if (data.study_date_time) {
          const study_date_timeArr = data.study_date_time.split(' ')
          this.studyDate = study_date_timeArr[0]
          this.studyTime = study_date_timeArr[1]
          this.originalStudyDate = study_date_timeArr[0]
          this.originalStudyTime = study_date_timeArr[1]
        }else {
          this.studyDate = ''
          this.studyTime = ''
          this.originalStudyDate = ''
          this.originalStudyTime = ''
        }
        this.$nextTick(() => {
          this.isFirstLoadAge = 2 // 首次加载前不触发watch
        })
      }
    },
    async updateImgModify () {
      // const studyDate = this.studyDate ? this.studyDate : ''
      // const studyTime = this.studyTime ? this.studyTime : ''
      // if (studyDate.length === 0) {
      //   this.imgModifyData.study_date_time = studyTime
      // } else if (studyTime.length === 0) {
      //   this.imgModifyData.study_date_time = studyDate
      // } else {
      //   this.imgModifyData.study_date_time = studyDate + ' ' + studyTime
      // }


      let delParams =   {
        patient_id: '',
        patient_name: '',
        other_patient_name: '',
        patient_sex: 'M',
        patient_birth_date:'',
        patient_age: '',
        accession_number: '',
        study_date_time: '',
        study_description: '',
        study_instance_uid: '',
        modalities_in_study: '',
      }
      for(let key in delParams)
      {
        delParams[key] = this.imgModifyData[key]
      }

      const params = {
        ...this.imgModifyData
      }
      
      if (params.id) {
        delete params.id
      }
      const res = await this.$pacsApi.pacsApi.updateImgModify(delParams, this.rowId)
      const { code, msg } = res
      if (code === 0) {
        this.$message({
          type: 'success',
          message: msg
        })
        this.ImgModifyClose()
        this.$emit('refreshTable')
      }
    },
    ImgModifySave (formName) {
      this.$refs[formName].validate((valid) => {
        if(valid) {
          // 检查日期 和 检查时间 没有变化,不进行提示
          if(this.studyDate === this.originalStudyDate && this.studyTime === this.originalStudyTime) {
            this.updateImgModify()
          }else {
            const h = this.$createElement
            this.$msgbox({
              message: h('div', { style: 'padding: 30px 35px 25px 60px' }, [
                h('div', null, [
                  h('i', { class: 'iconfont', style: 'display: inline-block;color: #EF8900;font-size:18px;margin-right: 11px;vertical-align: middle' }, '\ue687'),
                  h('span', { style: 'color: #EF8900' }, '确认要修改检查日期和检查时间信息？')
                ]),
                h('div', { style: 'color: #999; margin-left: 28px; margin-top: 10px; line-height: 20px' }, [
                  h('div', null, '检查日期和时间的修改功能仅用于影像设备时间发错误时。'),
                  h('div', null, '由于日期和时间被修改而导致的法律纠纷，我司不承担责任。')
                ])
              ]),
              showCancelButton: true,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                  done()
                } else {
                  done()
                }
              }
            }).then(action => {
              // this.$message({
              //   type: 'success',
              //   message: '删除成功!'
              // });
              this.updateImgModify()
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
          }
        }else {
          console.log('111')
          return false
        }
      })
    },
    ImgModifyClose () {
      this.$emit('ImgModifyClose', '')
    }
  }
}
</script>
